package com.nb.controller;

import com.nb.DTO.CaseDTO;
import com.nb.DTO.CaseQueryDTO;
import com.nb.DTO.CaseUpdateDTO;
import com.nb.VO.CaseDetailVO;
import com.nb.VO.CaseVO;
import com.nb.entity.CaseMaterial;
import com.nb.mapper.CaseMaterialMapper;
import com.nb.result.Result;
import com.nb.service.CaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.List;

@RestController
@RequestMapping("/case")
public class CaseController {

    @Autowired
    private CaseService caseService;
    @Autowired
    private CaseMaterialMapper caseMaterialMapper;

    /**
     * 案件申请
     *
     * @return
     */
    @PostMapping("/caseApplication")
    private Result caseApplication(CaseDTO caseDTO) {
        caseService.caseApplication(caseDTO);
        return Result.success();
    }

    /**
     * 案件列表
     *
     * @return
     */
    @GetMapping("/list")
    private Result caseList(CaseQueryDTO caseQueryDTO) {
        List<CaseVO> caseList = caseService.caseList(caseQueryDTO);
        return Result.success(caseList);
    }

    /**
     * 案件详情
     *
     * @param id
     * @return
     */
    @GetMapping("/detail/{id}")
    private Result caseDetail(@PathVariable Long id) {

        CaseDetailVO caseDetailVO = caseService.caseDetail(id);
        return Result.success(caseDetailVO);
    }

    /**
     * 案件材料下载
     *
     * @param materialId
     * @return
     */
    @GetMapping("/download/{materialId}")
    private ResponseEntity<Resource> caseMaterialDownload(@PathVariable Long materialId) {
        try {

            // 1. 根据案件ID查询文件信息
            CaseMaterial caseMaterial = caseMaterialMapper.selectOneById(materialId);

            // 2. 构建文件路径，当前项目路径+material.getStoragePath()
                String filePath = System.getProperty("user.dir") + caseMaterial.getStoragePath();
                File file = new File(filePath);

                Resource resource = new UrlResource(file.toURI());

            // 3. 返回文件流
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                    .body(resource);
        } catch (Exception e) {
            // 返回HTTP 500错误
            return ResponseEntity.status(500).body(null);
        }

    }


    /**
     * 案件更新
     *
     */
    @PutMapping("/update/{id}")
    private Result caseUpdate(@PathVariable Long id,@RequestBody CaseUpdateDTO caseUpdateDTO) {
        caseService.caseUpdate(id, caseUpdateDTO);
        return Result.success();
    }

}
